package com.xuetang.controller.api;

import com.xuetang.entity.*;
import com.xuetang.service.DietService;
import com.xuetang.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;

/**
 * 饮食管理API控制器
 */
@RestController
@RequestMapping("/api/diet")
public class DietController {

    @Autowired
    private DietService dietService;

    /**
     * 获取食物类别列表
     */
    @GetMapping("/categories")
    public Map<String, Object> getFoodCategories() {
        List<DietFoodCategory> categories = dietService.getFoodCategories();
        return ResultUtil.success(categories);
    }

    /**
     * 根据类别ID获取食物列表
     */
    @GetMapping("/foods/category/{categoryId}")
    public Map<String, Object> getFoodsByCategory(
            @PathVariable Integer categoryId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        Map<String, Object> result = dietService.getFoodsByCategory(categoryId, page, pageSize);
        return ResultUtil.success(result);
    }

    /**
     * 搜索食物
     */
    @GetMapping("/foods/search")
    public Map<String, Object> searchFoods(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        Map<String, Object> result = dietService.searchFoods(keyword, page, pageSize);
        return ResultUtil.success(result);
    }

    /**
     * 获取食物详情
     */
    @GetMapping("/foods/{id}")
    public Map<String, Object> getFoodDetail(@PathVariable Integer id) {
        DietFood food = dietService.getFoodDetail(id);
        return ResultUtil.success(food);
    }

    /**
     * 获取用户指定日期的饮食记录
     */
    @GetMapping("/records")
    public Map<String, Object> getDietRecord(
            @RequestParam Long userId,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date date) {
        DietRecord record = dietService.getDietRecord(userId, date);
        return ResultUtil.success(record);
    }

    /**
     * 获取用户饮食记录列表
     */
    @GetMapping("/records/list")
    public Map<String, Object> getDietRecords(
            @RequestParam Long userId,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        Map<String, Object> result = dietService.getDietRecords(userId, startDate, endDate, page, pageSize);
        return ResultUtil.success(result);
    }

    /**
     * 获取用户特定餐次的饮食记录
     */
    @RequestMapping(value = "/records/meal", method = { RequestMethod.GET, RequestMethod.POST })
    public Map<String, Object> getDietRecordsByMealType(
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date date,
            @RequestParam(required = false) String mealType,
            @RequestBody(required = false) Map<String, Object> params) {
        try {
            // 处理GET请求和POST请求的不同参数格式
            if (params != null) {
                // POST请求
                userId = Long.parseLong(params.get("userId").toString());
                date = new java.text.SimpleDateFormat("yyyy-MM-dd").parse(params.get("date").toString());
                mealType = params.get("mealType").toString();
            } else if (userId == null || date == null || mealType == null) {
                return ResultUtil.error("参数不能为空");
            }

            DietRecord record = dietService.getDietRecord(userId, date);

            // 将mealType保存为final变量，以便在lambda表达式中使用
            final String finalMealType = mealType;

            if (record != null && record.getMeals() != null) {
                // 过滤出指定餐次类型的记录
                List<DietRecordDetail> mealRecords = record.getMeals().stream()
                        .filter(detail -> finalMealType.equals(detail.getMealType()))
                        .collect(java.util.stream.Collectors.toList());

                // 计算该餐次的营养摄入总量
                BigDecimal totalCalories = BigDecimal.ZERO;
                BigDecimal totalCarbs = BigDecimal.ZERO;
                BigDecimal totalProtein = BigDecimal.ZERO;
                BigDecimal totalFat = BigDecimal.ZERO;

                for (DietRecordDetail detail : mealRecords) {
                    if (detail.getCalories() != null)
                        totalCalories = totalCalories.add(detail.getCalories());
                    if (detail.getCarbs() != null)
                        totalCarbs = totalCarbs.add(detail.getCarbs());
                    if (detail.getProtein() != null)
                        totalProtein = totalProtein.add(detail.getProtein());
                    if (detail.getFat() != null)
                        totalFat = totalFat.add(detail.getFat());
                }

                Map<String, Object> result = new HashMap<>();
                result.put("records", mealRecords);
                result.put("totalCalories", totalCalories);
                result.put("totalCarbs", totalCarbs);
                result.put("totalProtein", totalProtein);
                result.put("totalFat", totalFat);

                return ResultUtil.success(result);
            } else {
                return ResultUtil.success(new HashMap<String, Object>() {
                    {
                        put("records", new ArrayList<>());
                        put("totalCalories", 0);
                        put("totalCarbs", 0);
                        put("totalProtein", 0);
                        put("totalFat", 0);
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error("获取饮食记录失败: " + e.getMessage());
        }
    }

    /**
     * 添加饮食记录
     */
    @PostMapping("/records")
    public Map<String, Object> addDietRecord(@RequestBody Map<String, Object> params) {
        try {
            // 检查必要参数
            if (params == null) {
                return ResultUtil.error("请求参数不能为空");
            }

            if (!params.containsKey("userId") || params.get("userId") == null) {
                return ResultUtil.error("用户ID不能为空");
            }

            if (!params.containsKey("foodId") || params.get("foodId") == null) {
                return ResultUtil.error("食物ID不能为空");
            }

            // 创建饮食记录对象
            DietRecord record = new DietRecord();
            // 设置用户ID
            record.setUserId(Long.parseLong(params.get("userId").toString()));

            // 处理日期和时间
            Date mealTime = new Date(); // 默认为当前时间
            try {
                if (params.containsKey("date") && params.get("date") != null) {
                    String dateStr = params.get("date").toString();
                    String timeStr = params.containsKey("time") && params.get("time") != null
                            ? params.get("time").toString()
                            : "00:00";

                    // 合并日期和时间
                    String dateTimeStr = dateStr + " " + timeStr;
                    mealTime = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm").parse(dateTimeStr);
                }
            } catch (Exception e) {
                System.out.println("日期解析错误，使用当前时间: " + e.getMessage());
            }
            record.setMealTime(mealTime);

            // 设置餐次类型
            String mealTypeStr = params.containsKey("mealType") ? params.get("mealType").toString() : "breakfast";
            int mealTypeVal = 0; // 默认为早餐
            switch (mealTypeStr) {
                case "breakfast":
                    mealTypeVal = 0;
                    break;
                case "lunch":
                    mealTypeVal = 1;
                    break;
                case "dinner":
                    mealTypeVal = 2;
                    break;
                case "snack":
                    mealTypeVal = 3;
                    break;
            }
            record.setMealType(mealTypeVal);

            // 从食物信息服务获取食物详情
            Integer foodId = Integer.parseInt(params.get("foodId").toString());
            DietFood food = dietService.getFoodDetail(foodId);
            if (food == null) {
                return ResultUtil.error("未找到指定的食物信息");
            }

            // 设置食物信息
            record.setFoodName(food.getName());

            // 计算摄入量和营养素
            double quantity = params.containsKey("amount") && params.get("amount") != null
                    ? Double.parseDouble(params.get("amount").toString())
                    : 100.0;
            double ratio = quantity / 100.0; // 标准100g的比例

            // 设置卡路里和营养成分
            record.setCalories(BigDecimal.valueOf(food.getCalories().doubleValue() * ratio));
            record.setCarbohydrate(BigDecimal.valueOf(food.getCarbs().doubleValue() * ratio));
            record.setProtein(BigDecimal.valueOf(food.getProtein().doubleValue() * ratio));
            record.setFat(BigDecimal.valueOf(food.getFat().doubleValue() * ratio));
            record.setFoodImage(food.getImage());

            // 设置备注
            record.setRemark(params.containsKey("remark") ? (String) params.get("remark") : "");

            // 创建明细记录
            List<DietRecordDetail> details = new ArrayList<>();
            DietRecordDetail detail = new DietRecordDetail();
            detail.setFoodId(foodId);
            detail.setMealType(mealTypeStr);
            detail.setMealTime(mealTime);
            detail.setQuantity(new BigDecimal(quantity));
            detail.setCalories(record.getCalories());
            detail.setCarbs(record.getCarbohydrate());
            detail.setProtein(record.getProtein());
            detail.setFat(record.getFat());
            detail.setFoodName(food.getName());
            detail.setFoodImage(food.getImage());
            detail.setFoodUnit(food.getUnit());
            details.add(detail);

            // 保存记录
            boolean success = dietService.addDietRecord(record, details);
            return success ? ResultUtil.success() : ResultUtil.error("添加饮食记录失败");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error("添加饮食记录失败: " + e.getMessage());
        }
    }

    /**
     * 更新饮食记录
     */
    @PutMapping("/records/{id}")
    public Map<String, Object> updateDietRecord(
            @PathVariable Long id,
            @RequestBody Map<String, Object> params) {
        try {
            DietRecord record = new DietRecord();
            record.setId(id);
            record.setUserId(Long.parseLong(params.get("userId").toString()));
            record.setMealTime(new Date()); // 从请求体获取或使用当前日期
            record.setMealType(Integer.parseInt(params.get("mealType").toString()));
            record.setFoodName((String) params.get("foodName"));
            record.setCalories(new BigDecimal(params.get("calories").toString()));
            record.setCarbohydrate(new BigDecimal(params.get("carbohydrate").toString()));
            record.setProtein(new BigDecimal(params.get("protein").toString()));
            record.setFat(new BigDecimal(params.get("fat").toString()));
            record.setFoodImage((String) params.get("foodImage"));
            record.setRemark((String) params.get("remark"));

            @SuppressWarnings("unchecked")
            List<Map<String, Object>> mealsData = (List<Map<String, Object>>) params.get("meals");
            List<DietRecordDetail> details = convertMealsToDetails(mealsData);

            boolean success = dietService.updateDietRecord(record, details);
            return success ? ResultUtil.success() : ResultUtil.error("更新饮食记录失败");
        } catch (Exception e) {
            return ResultUtil.error("更新饮食记录失败: " + e.getMessage());
        }
    }

    /**
     * 删除饮食记录
     */
    @DeleteMapping("/records/{id}")
    public Map<String, Object> deleteDietRecord(@PathVariable Long id) {
        boolean success = dietService.deleteDietRecord(id);
        return success ? ResultUtil.success() : ResultUtil.error("删除饮食记录失败");
    }

    /**
     * 获取推荐食谱列表
     */
    @GetMapping("/recipes/recommend")
    public Map<String, Object> getRecommendRecipes(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        Map<String, Object> result = dietService.getRecommendRecipes(page, pageSize);
        return ResultUtil.success(result);
    }

    /**
     * 根据餐类型获取食谱列表
     */
    @GetMapping("/recipes/mealType/{mealType}")
    public Map<String, Object> getRecipesByMealType(
            @PathVariable String mealType,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        Map<String, Object> result = dietService.getRecipesByMealType(mealType, page, pageSize);
        return ResultUtil.success(result);
    }

    /**
     * 获取食谱详情
     */
    @GetMapping("/recipes/{id}")
    public Map<String, Object> getRecipeDetail(@PathVariable Integer id) {
        DietRecipe recipe = dietService.getRecipeDetail(id);
        return ResultUtil.success(recipe);
    }

    /**
     * 获取用户饮食统计数据
     */
    @GetMapping("/stats")
    public Map<String, Object> getDietStats(
            @RequestParam Long userId,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate) {
        Map<String, Object> stats = dietService.getDietStats(userId, startDate, endDate);
        return ResultUtil.success(stats);
    }

    /**
     * 添加食谱
     */
    @PostMapping("/recipes")
    public Map<String, Object> addRecipe(@RequestBody Map<String, Object> params) {
        try {
            // 参数校验
            if (params == null) {
                return ResultUtil.error("请求参数不能为空");
            }

            // 检查必要字段
            if (!params.containsKey("title") || params.get("title") == null ||
                    String.valueOf(params.get("title")).trim().isEmpty()) {
                return ResultUtil.error("食谱标题不能为空");
            }

            DietRecipe recipe = new DietRecipe();
            recipe.setTitle(String.valueOf(params.get("title")).trim());
            recipe.setDescription(params.containsKey("description") ? String.valueOf(params.get("description")) : "");
            recipe.setImage(params.containsKey("image") ? String.valueOf(params.get("image")) : "");
            recipe.setMealType(params.containsKey("mealType") ? String.valueOf(params.get("mealType")) : "");
            recipe.setTips(params.containsKey("tips") ? String.valueOf(params.get("tips")) : "");

            // 处理准备时间和烹饪时间
            if (params.containsKey("prepTime") && params.get("prepTime") != null) {
                try {
                    recipe.setPrepTime(Integer.parseInt(String.valueOf(params.get("prepTime"))));
                } catch (NumberFormatException e) {
                    recipe.setPrepTime(10); // 默认10分钟
                }
            } else {
                recipe.setPrepTime(10); // 默认10分钟
            }

            if (params.containsKey("cookTime") && params.get("cookTime") != null) {
                try {
                    recipe.setCookTime(Integer.parseInt(String.valueOf(params.get("cookTime"))));
                } catch (NumberFormatException e) {
                    recipe.setCookTime(20); // 默认20分钟
                }
            } else {
                recipe.setCookTime(20); // 默认20分钟
            }

            // 处理食材明细
            List<DietRecipeDetail> details = new ArrayList<>();
            if (params.containsKey("foods") && params.get("foods") instanceof List) {
                @SuppressWarnings("unchecked")
                List<Map<String, Object>> foodsData = (List<Map<String, Object>>) params.get("foods");

                int sortOrder = 1;
                for (Map<String, Object> food : foodsData) {
                    if (food.containsKey("foodId")) {
                        DietRecipeDetail detail = new DietRecipeDetail();
                        detail.setFoodId(Integer.parseInt(String.valueOf(food.get("foodId"))));
                        detail.setQuantity(new BigDecimal(String.valueOf(food.getOrDefault("quantity", "100"))));
                        detail.setUnit(String.valueOf(food.getOrDefault("unit", "g")));
                        detail.setSortOrder(sortOrder++);
                        details.add(detail);
                    }
                }
            }

            // 处理烹饪步骤
            List<DietRecipeStep> steps = new ArrayList<>();
            if (params.containsKey("steps") && params.get("steps") instanceof List) {
                @SuppressWarnings("unchecked")
                List<Map<String, Object>> stepsData = (List<Map<String, Object>>) params.get("steps");

                int stepOrder = 1;
                for (Map<String, Object> step : stepsData) {
                    if (step.containsKey("content")) {
                        DietRecipeStep recipeStep = new DietRecipeStep();
                        recipeStep.setContent(String.valueOf(step.get("content")));
                        recipeStep.setStepOrder(
                                step.containsKey("stepOrder") ? Integer.parseInt(String.valueOf(step.get("stepOrder")))
                                        : stepOrder++);
                        recipeStep.setImage(step.containsKey("image") ? String.valueOf(step.get("image")) : null);
                        steps.add(recipeStep);
                    }
                }
            }

            // 设置步骤
            recipe.setSteps(steps);

            boolean success = dietService.addRecipe(recipe, details);
            return success ? ResultUtil.success() : ResultUtil.error("添加食谱失败");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error("添加食谱失败: " + e.getMessage());
        }
    }

    /**
     * 更新食谱
     */
    @PutMapping("/recipes/{id}")
    public Map<String, Object> updateRecipe(
            @PathVariable Integer id,
            @RequestBody Map<String, Object> params) {
        try {
            // 参数校验
            if (params == null) {
                return ResultUtil.error("请求参数不能为空");
            }

            // 检查必要字段
            if (!params.containsKey("title") || params.get("title") == null ||
                    String.valueOf(params.get("title")).trim().isEmpty()) {
                return ResultUtil.error("食谱标题不能为空");
            }

            DietRecipe recipe = new DietRecipe();
            recipe.setId(id);
            recipe.setTitle(String.valueOf(params.get("title")).trim());
            recipe.setDescription(params.containsKey("description") ? String.valueOf(params.get("description")) : "");
            recipe.setImage(params.containsKey("image") ? String.valueOf(params.get("image")) : "");
            recipe.setMealType(params.containsKey("mealType") ? String.valueOf(params.get("mealType")) : "");
            recipe.setTips(params.containsKey("tips") ? String.valueOf(params.get("tips")) : "");

            // 处理准备时间和烹饪时间
            if (params.containsKey("prepTime") && params.get("prepTime") != null) {
                try {
                    recipe.setPrepTime(Integer.parseInt(String.valueOf(params.get("prepTime"))));
                } catch (NumberFormatException e) {
                    recipe.setPrepTime(10); // 默认10分钟
                }
            } else {
                recipe.setPrepTime(10); // 默认10分钟
            }

            if (params.containsKey("cookTime") && params.get("cookTime") != null) {
                try {
                    recipe.setCookTime(Integer.parseInt(String.valueOf(params.get("cookTime"))));
                } catch (NumberFormatException e) {
                    recipe.setCookTime(20); // 默认20分钟
                }
            } else {
                recipe.setCookTime(20); // 默认20分钟
            }

            // 处理食材明细
            List<DietRecipeDetail> details = new ArrayList<>();
            if (params.containsKey("foods") && params.get("foods") instanceof List) {
                @SuppressWarnings("unchecked")
                List<Map<String, Object>> foodsData = (List<Map<String, Object>>) params.get("foods");

                int sortOrder = 1;
                for (Map<String, Object> food : foodsData) {
                    if (food.containsKey("foodId")) {
                        DietRecipeDetail detail = new DietRecipeDetail();
                        detail.setFoodId(Integer.parseInt(String.valueOf(food.get("foodId"))));
                        detail.setQuantity(new BigDecimal(String.valueOf(food.getOrDefault("quantity", "100"))));
                        detail.setUnit(String.valueOf(food.getOrDefault("unit", "g")));
                        detail.setSortOrder(sortOrder++);
                        details.add(detail);
                    }
                }
            }

            // 处理烹饪步骤
            List<DietRecipeStep> steps = new ArrayList<>();
            if (params.containsKey("steps") && params.get("steps") instanceof List) {
                @SuppressWarnings("unchecked")
                List<Map<String, Object>> stepsData = (List<Map<String, Object>>) params.get("steps");

                int stepOrder = 1;
                for (Map<String, Object> step : stepsData) {
                    if (step.containsKey("content")) {
                        DietRecipeStep recipeStep = new DietRecipeStep();
                        recipeStep.setContent(String.valueOf(step.get("content")));
                        recipeStep.setStepOrder(
                                step.containsKey("stepOrder") ? Integer.parseInt(String.valueOf(step.get("stepOrder")))
                                        : stepOrder++);
                        recipeStep.setImage(step.containsKey("image") ? String.valueOf(step.get("image")) : null);
                        steps.add(recipeStep);
                    }
                }
            }

            // 设置步骤
            recipe.setSteps(steps);

            boolean success = dietService.updateRecipe(recipe, details);
            return success ? ResultUtil.success() : ResultUtil.error("更新食谱失败");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error("更新食谱失败: " + e.getMessage());
        }
    }

    /**
     * 将前端传入的餐食数据转换为饮食记录明细对象
     */
    private List<DietRecordDetail> convertMealsToDetails(List<Map<String, Object>> mealsData) {
        List<DietRecordDetail> details = new java.util.ArrayList<>();

        if (mealsData != null) {
            for (Map<String, Object> meal : mealsData) {
                DietRecordDetail detail = new DietRecordDetail();
                detail.setFoodId(Integer.parseInt(meal.get("foodId").toString()));
                detail.setMealType((String) meal.get("mealType"));
                // 处理可能的日期格式问题
                if (meal.get("mealTime") != null) {
                    try {
                        detail.setMealTime(new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                                .parse(meal.get("mealTime").toString()));
                    } catch (Exception e) {
                        detail.setMealTime(new Date());
                    }
                } else {
                    detail.setMealTime(new Date());
                }
                detail.setQuantity(new java.math.BigDecimal(meal.get("quantity").toString()));

                // 如果有卡路里等营养成分信息，则设置
                if (meal.get("calories") != null) {
                    detail.setCalories(new java.math.BigDecimal(meal.get("calories").toString()));
                }
                if (meal.get("carbs") != null) {
                    detail.setCarbs(new java.math.BigDecimal(meal.get("carbs").toString()));
                }
                if (meal.get("protein") != null) {
                    detail.setProtein(new java.math.BigDecimal(meal.get("protein").toString()));
                }
                if (meal.get("fat") != null) {
                    detail.setFat(new java.math.BigDecimal(meal.get("fat").toString()));
                }

                // 如果有血糖值数据，则设置
                if (meal.get("bloodSugarBefore") != null) {
                    detail.setBloodSugarBefore(new java.math.BigDecimal(meal.get("bloodSugarBefore").toString()));
                }
                if (meal.get("bloodSugarAfter") != null) {
                    detail.setBloodSugarAfter(new java.math.BigDecimal(meal.get("bloodSugarAfter").toString()));
                }

                details.add(detail);
            }
        }

        return details;
    }
}